# -*- coding: utf-8 -*- 
"""
========================================================================================================================
@project : my-sanic
@file: myMiddleware
@Author: mengying
@email: 652044581@qq.com
@date: 2023/3/3 11:34
@desc: 系统的中间件
========================================================================================================================
"""
from sanic import Sanic
from config import config
from MyUtils.myLog import SeqLog
import time
import traceback

app = Sanic.get_app(config.PROJECT_NAME)
logger = SeqLog().get_logger()


@app.middleware('request')
def process_request(request):
    request.headers['my-duration'] = time.time()


@app.middleware('response')
def process_response(request, response):
    duration = time.time() - request.headers['my-duration']
    response.headers['my-duration'] = duration
    data = {'链路id': request.id.hex, "接口": request.path, "方式": request.method, '接口耗时:': str(duration)}
    logger.info(str(data))


@app.exception(Exception)
def process_error(request, exception):
    print(traceback.format_exc())
